import React, { Component } from 'react';
import { toJS } from 'mobx';
import { withRouter } from 'react-router-dom';
import { inject, observer } from 'mobx-react';
import {
  Flex,
  Popover,
  Checkbox,
  Button,
  Icon,
  Avatar,
  ActionSheet,
  Tools,
  List,
  Modal
} from 'weaver-mobile';
const getLabel = Tools.getLabel
const PopoverItem = Popover.Item;
const isIPhone = new RegExp('\\biPhone\\b|\\biPod\\b', 'i').test(
  window.navigator.userAgent
);
const alert = Modal.alert;
let wrapProps;
if (isIPhone) {
  wrapProps = {
    onTouchStart: e => e.preventDefault(),
  };
}
@withRouter
@observer
class WrCardList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      popoverVisible: false,
      itemCheckBoxSelected: [],
      datas: [],
    };
  }
  componentWillMount() {
    this.setState({ datas: this.props.dataList });
  }
  componentWillReceiveProps(nextProps) {
    if (nextProps.dataList !== this.props.dataList) {
      this.setState({ datas: nextProps.dataList });
    }
  }

  showActionSheet = index => {
    let { dropList } = this.props;
    let items = [];
    let _ = this
    if (dropList && dropList.length > 0) {
      dropList.map(d => {
        items.push({
          content: d.title,
          onClick: () => {
            d.func(index)
            if(d.key=='delete'){
              _.setState({itemCheckBoxSelected:[]})
            }
          },
        });
      });
    }
    items.push({
      content: getLabel(31129,'取消'),
    });
    ActionSheet.showActionSheetWithOptions(
      {
        options: items,
        cancelButtonIndex: items.length - 1, //取消按钮的索引位置
        // destructiveButtonIndex: BUTTONS.length - 2,
        // title: 'title',
        // message: 'I am description, description, description',
        maskClosable: true, //点击蒙层是否允许关闭，默认允许
        'data-seed': 'logId',
        wrapProps,
      },
      buttonIndex => {
        this.setState({ clicked: items[buttonIndex] });
      }
    );
  };

  onPopoverSelect = (node, index, i) => {
    const { dropList } = this.props;
    if (dropList[index] && typeof dropList[index].func(i) == 'function') {
      dropList[index].func(i);
     
    }
    this.setState({ popoverVisible: false });
  };

  onAdd = () => {
    const { onAdd } = this.props;
    onAdd();
  };
  onDelete = () => {
    let _ = this
    let { itemCheckBoxSelected, datas } = this.state;
    if (itemCheckBoxSelected.length < 1) {
      return;
    } else {
      alert(getLabel('386786', '信息确认'), getLabel(388758, '确认要删除吗？'), [
        { text: getLabel(31129, '取消'), onPress: () => { } },
        {
          text: getLabel(826, '确定'),
          onPress: () => {
            _.deleteEvent()
          },
        },
      ])
    }

    
  };
  deleteEvent=()=>{
    let { onDelete } = this.props;
    let { itemCheckBoxSelected, datas } = this.state;
    if (itemCheckBoxSelected.length < 1) {
      return;
    } else {
      itemCheckBoxSelected.map(v => {
        delete datas[v];
      });
      datas = datas.filter(d => {
        return d != undefined;
      });
      this.setState({ datas, itemCheckBoxSelected: [] });
      onDelete(datas);
    }
  }

  onItemCheckBoxChange = e => {
    let { itemCheckBoxSelected } = this.state;
    if (itemCheckBoxSelected.indexOf(e) > -1) {
      itemCheckBoxSelected.splice(itemCheckBoxSelected.indexOf(e), 1);
    } else {
      itemCheckBoxSelected.push(e);
    }
    this.setState({ itemCheckBoxSelected });
  };

  getDropItems = () => {
    let { dropList } = this.props;
    let dropItems = [];
    dropList.map(d => {
      dropItems.push(
        <PopoverItem key={d.title} value="scan" data-seed="logId">
          {d.title}
        </PopoverItem>
      );
    });
    return dropItems;
  };

  render() {
    let {
      dataMapList,
      title,
      showAdd,
      showDelete,
      showCheckBox,
      showContent,
      dropItemType,
      hiddenHeader,
      full,
      showDropList,
      onRowClick
    } = this.props;
    let { itemCheckBoxSelected, datas } = this.state;
    const preCls = `wea-workrelate-mobile-cardlist-`;
    return (
      <div className={`${preCls}container`} style={{ margin: full ? '0' : "15px" }}>
        {hiddenHeader != "undefined" && !hiddenHeader &&
          <div>
            {
              !full &&<div className={`${preCls}header ${full?'':'wea-workrelate-mobile-noBottomBorder'}`  } >
              <div>{title}</div>
            </div>
            }
            
            {(showDelete || showAdd) && <div className={`${preCls}batch-operation ${full?'':'wea-workrelate-mobile-noBottomBorder'}`}>
                <span className={`${preCls}header-title`}>{getLabel(500410, "批量操作")}</span>
                <div className={`${preCls}header-operation`}>
                {showAdd &&
                  // <Icon size="xxs" onClick={this.onAdd} type='plus' color='#fff' className={`${preCls}header-operation-icon`}></Icon>
                  <span onClick={this.onAdd} className={`${preCls}header-operation-icon`}>+</span>
                }
                {showDelete &&
                <span
                style={{
                  backgroundColor: itemCheckBoxSelected.length > 0
                    ? '#55A1F8'
                    : '#999999',
                }}
                onClick={this.onDelete} className={`${preCls}header-operation-icon`}>-</span>
                  // <Icon
                  //   style={{
                  //     backgroundColor: itemCheckBoxSelected.length > 0
                  //       ? '#55A1F8'
                  //       : '#999999',
                  //   }}
                  //   onClick={this.onDelete} type='minus' color='#fff' className={`${preCls}header-operation-icon`}></Icon>
                }


              </div>
            </div>
            }
          </div>
        }

        <div className={`${preCls}content ${full?'':"wea-workrelate-mobile-full-border"}`} style={{ display:showContent?'block':'none'  }}>
          {datas &&
            datas.length > 0 &&
            datas.map((d, i) => {
              return (
                <div className={`${preCls}card-container`} key={i} style={i == (datas.length - 1) ? { margin: '0px',borderBottom:'0px' } : { opacity: '1' }}>
                  <div className={`${preCls}card-header`}>
                    <div className={`${preCls}card-header-title`}>
                      {showCheckBox &&
                        <Checkbox
                          checked={itemCheckBoxSelected.indexOf(i) > -1}
                          onChange={() => this.onItemCheckBoxChange(i)}
                        />}
                      <span
                        className={`${preCls}card-header-title-text`}
                        style={{marginLeft:(showCheckBox?'10px':'0px')}}
                    >{`${getLabel('15486','序号') }:`}<span 
                    className={showCheckBox? `${preCls}card-header-title-order-30`:`${preCls}card-header-title-order-60`}
                    >{` ${i + 1}`}</span></span>
                    </div>
                    <div className={`${preCls}card-header-operation`}>
                      {showDropList != undefined && showDropList && (dropItemType == 'actionSheet'
                        ? <Icon
                          type="ellipsis"
                          onClick={() => this.showActionSheet(i)}
                        />
                        : <Popover
                          mask
                          overlayClassName="fortest"
                          overlayStyle={{ color: 'currentColor' }}
                          visible={this.state.popoverVisible}
                          overlay={this.getDropItems()}
                          align={{
                            overflow: { adjustY: 0, adjustX: 0 },
                            offset: [-10, 0],
                          }}
                          onVisibleChange={() => {
                            this.setState({ popoverVisible: false });
                          }}
                          onSelect={(node, index) =>
                            this.onPopoverSelect(node, index, i)}
                        >
                          <div
                            className={`${preCls}card-header-operation-icon`}
                          >
                            <Icon type="ellipsis" />
                          </div>
                        </Popover>)}

                    </div>
                  </div>
                  <div className={`${preCls}card-content`} onClick={() => onRowClick(d,i)} style={{ padding:  "10px",borderBottom:(i==datas.length-1?'0px':'') }}>
                    {dataMapList &&
                      dataMapList.length > 0 &&
                      dataMapList.map(m => {
                        return Object.keys(d).map(k => {
                          if (m.fieldname == k) {
                            return (
                                <List.FormItem
                                    label={m.showname + ':'}
                                    noBorder
                                    line
                                    content={
                                      d[k] ? (m.method?m.method(d):<span dangerouslySetInnerHTML={{ __html: d[k].toString().replace(/\n/g,"<br/>") }}/>):''
                                    }
                                />
                            );
                          }
                        });
                      })}

                  </div>
                </div>
              );
            })}
          {datas.length < 1 && this.props.emptyComponent}

        </div>
      </div>
    );
  }
}
WrCardList.defaultProps = {
  title: '计划',
  dropItemType: 'actionSheet',
  dataMapList: [
  ],
  dataList: [
  ],
  onAdd: () => { },
  onDelete: e => {
  },
  dropList: [],
  emptyComponent: (
    <div
    >
    </div>
  ),
  showAdd: true,
  showDelete: true,
  showCheckBox: true,
  showDropList: true,
  showContent:true
};

export default WrCardList;
